package com.kamistoat.meimeimall.meimeimallproduct.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

// 用@EnableConfigurationProperties(CacheProperties.class)绑定一个库配置文件类
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class RedisCacheConfig {

    /**
     * 自定义的RedisCacheConfiguration
     * 输入值就是当前配置类绑定的配置文件类
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        // 直接把默认的RedisCacheConfiguration获取来，在默认配置上进行修改
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 要用覆盖写法，config=config.重新复制赋值
        // 希望redis中的键值对是<String,JSONString>的形式
        // 首先配置键的序列化机制，一直到最后的new前都是固定写法，使用String序列化机制使用 new StringRedisSerializer()
        config = config.serializeKeysWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                        new StringRedisSerializer()
                ));
        // 配置键值的序列化机制，一直到new前都是固定写法。使用Spring自带的JSON序列化机制就用new GenericJackson2JsonRedisSerializer()
        // 使用阿里巴巴的fastJSON则使用 new GenericJacksonJsonRedisSerializer()
        config = config.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                        // new GenericJackson2JsonRedisSerializer()
                        new GenericFastJsonRedisSerializer()
                ));
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }

        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }

        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }

        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
